package com.th.cash.th2.userliving

import ai.braininfra.video.LivenessManage
import ai.braininfra.video.utils.DetectAction
import ai.braininfra.video.utils.LivenessDetectListener
import ai.braininfra.video.utils.ResultData
import android.content.Intent
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lxj.xpopup.XPopup
import com.th.basemodel.base.BaseVB2Activity2
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.gotoActivity
import com.th.basemodel.ext.toast
import com.th.cash.th2.h5.H5Activity
import com.th.cash.th2.splash.PermissionDeniedPopup
import com.th.resmodel.databinding.ActivityUserLivingBinding
import kotlinx.coroutines.launch

//活体页
class UserLivingActivity : BaseVB2Activity2<ActivityUserLivingBinding>() {

    private var pId = ""
    private var rId = ""
    private var taskId = ""

    companion object {
        var PID = "pid"
    }

    private val mViewModel by viewModels<UserLivingVm>()

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    override fun setWindowPadding() {
        ViewCompat.setOnApplyWindowInsetsListener(mBinding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, 0, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun getDataFromIntent(intent: Intent) {
        pId = intent.getStringExtra(PID) ?: ""
    }

    override fun init() {
        initTitle()
        initClick()
        mViewModel.intentChannel.trySend(UserLivingIntent.LivingInit(LivingInitRequest(pId)))
    }

    private fun initClick() {
        mBinding.tvUserLivingSubmit.setOnClickListener {
            if (!TextUtils.isEmpty(rId)) {
                gotoActivity<H5Activity>()
            } else {
                requestPermission()
            }
        }

        mBinding.header.headBack.setOnClickListener {
            finish()
        }
    }

    override fun observeViewModel() {
        lifecycleScope.launch {
            mViewModel.uiState.collect {
                when (it) {
                    is UserLivingState.Idle -> {

                    }

                    is UserLivingState.Init -> {
                        rId = it.response.liveness?.PxGEecSAntiwarMrDXISc ?: ""
                        taskId = it.response.liveness?.wVMLtprPhotocoagulatingIKLgSnS ?: ""

                    }

                    is UserLivingState.StartLiving -> {
                        startLiving()
                    }

                    is UserLivingState.LivingSuccess -> {
                        gotoActivity<H5Activity>()
                        finish()
                    }

                    else -> {}
                }
            }
        }
    }

    private fun startLiving() {
        //构建FaceLiveness
        val build = LivenessManage.Builder(this)
            .setActionList(
                DetectAction.SHAKE,
//                DetectAction.OPENMOUTH,
                DetectAction.BLINK
            ) // 动作顺序，支持1-3个动作
            .setVideoTime(2000) // 设置每个动作视频时长
//            .setIsEnglish(true) // * 设置是否是英文，默认为对应国家语言的sdk,设置为英文后强制转换成英文,英文版sdk不用设置此内容
            .setShuffle(true) // 设置是否打乱action list 设置的动作顺序
            .build()
        build.show(object : LivenessDetectListener {
            override fun onStart() {
            }


            override fun onShow() {
            }


            override fun onDismiss() {
            }


            override fun onActionDetect(detectAction: DetectAction) {
            }


            override fun onError(msg: String) {
                toast(msg)
                mBinding.ivUserLivingIcon.setBackgroundResource(com.th.resmodel.R.mipmap.img_37)
            }

            override fun onFinish(resultData: ResultData) {
                mViewModel.intentChannel.trySend(
                    UserLivingIntent.UploadData(
                        pId,
                        taskId,
                        resultData
                    )
                )
            }
        })
    }

    private fun initTitle() {
        mBinding.header.headTitle.text = "การรับรอง"
    }


    private fun requestPermission() {
        XXPermissions.with(this)
            // 申请单个权限
            .permission(
                Permission.CAMERA
            )
            // 申请多个权限
            //            .permission(Permission.Group.CALENDAR)
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            .unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        toast("ไม่ได้รับอนุญาตอย่างถูกต้อง")
                        return
                    }
                    mViewModel.intentChannel.trySend(
                        UserLivingIntent.LivingLimit(
                            LivingLimitRequest(
                                pId
                            )
                        )
                    )
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        showPermissionDeniedPopup(permissions)
                    } else {
                        toast("ไม่ได้รับอนุญาตอย่างถูกต้อง")
                    }
                }
            })
    }

    private fun showPermissionDeniedPopup(permissions: MutableList<String>) {
        XPopup.Builder(this)
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(PermissionDeniedPopup(this).run {

                clickListener = { agree ->
                    if (agree) {
                        XXPermissions.startPermissionActivity(context, permissions)
                    }
                }

                this
            })
            .show()
    }
}